// pages/reservation/index.js
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    domTop: 0,
    isDomTop: false,
    toView: '',
    listDate: null, // 暂存的
    fileList: null, // 暂存的
    listIndex: 0,
    selectFile: [],
    selectFileObj: {},
    isView: false,
    list: [],
    type:null,//根据type来显示早午晚。id分别为1/2/3
    typeName:'',
    imgArr: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      type:options.type
    })
    this.getList();
    this.fileList();
    this.getBanner();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let self = this;
    wx.createSelectorQuery().select('#quer').boundingClientRect(function(rect){
      console.log('rest:', rect)
      self.setData({domTop: rect.top})
    }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let book = wx.getStorageSync('book');
    if (book) {
      let obj = {};
      for (let i = 0; i < book.length; i++) {
        obj[book[i].id] = book[i].id;
      }
      this.setData({
        selectFile: book,
        selectFileObj: obj
      })
    } else  {
      this.setData({
        selectFile: [],
        selectFileObj: {}
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getList();
    this.fileList();
    this.getBanner();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 监听滚动 
   */
  onPageScroll: function (e) {
    if (this.data.isDomTop) {
      if (e.scrollTop < (this.data.domTop - 5)) this.setData({isDomTop: false});
    } else {
      if (e.scrollTop > (this.data.domTop - 5)) this.setData({isDomTop: true});
    }
    
  },
  // 获取banner
  getBanner() {
    let url = 'mp/banner/list';
    App.ajax(url, 'GET').then(res => {
      console.log('banner数据', res);
      if (res.status === 10000) {
        this.setData({
          imgArr: res.data
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },

  // 自定义方法
  reservation(e) {
    console.log(e);
    let item = e.currentTarget.dataset.list;
    let selectFile = JSON.parse(JSON.stringify(this.data.selectFile));
    let selectFileObj = JSON.parse(JSON.stringify(this.data.selectFileObj));
    let index = selectFile.findIndex(val => {return val.id === item.id});
    if (index === -1) {
      if (selectFile.length !== 0) {
        wx.showToast({
          title: '一次只能预约一个套餐哦',
          icon: 'none',
          duration: 2000
        })
        return false;
      }
      selectFile.push(item);
      selectFileObj[item.id] = item.id;
    } else {
      selectFile.splice(index, 1);
      delete selectFileObj[item.id];
    }
    this.setData({
      selectFile: selectFile,
      selectFileObj: selectFileObj
    })
  },
  lower(e) {
    console.log('加载更多', e)
  },
  showList(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index;
    this.setData({
      listIndex: index,
      toView: 'scroll' + index
    });
  },
  upView(e) {
    let val = e.currentTarget.dataset.val;
    if (e.currentTarget.dataset.up) val = this.data.isView ? false : true;
    this.setData({
      isView: val
    })
  },
  closeFile() {
    wx.removeStorage({
      key: 'book',
    })
    this.setData({
      selectFileObj: {},
      selectFile: []
    })
  },
  goInfo(e) {
    let item = e.currentTarget.dataset.item;
    let param = {
      id: item.id,
      c_id: item.c_id
    };
    wx.navigateTo({
      url: '/pages/order/info/index?param=' + JSON.stringify(param),
    })
  },
  goOrder() {
    if (this.data.selectFile.length === 0) return false;
    let arr = [];
    let list = this.data.selectFile;
    for (let i = 0; i < list.length; i++) {
      let date = {
        id: list[i].id,
        quantity: list[i].number
      }
      arr.push(date);
    }
    let param = {
      dishesList: arr,
      type: 1,
      remark: ''
    };
    wx.showModal({
      title: `是否确认预约[${this.data.selectFile[0].name}]？`,
      showCancel: true,
      success: (val) => {
        if (val.confirm){
          let url = 'mp/order';
          App.ajax(url, 'post', param).then(res => {
            if (res.status === 10000) {
              let day = App.util.formatDate(new Date(), 'YMD');
              let storage = wx.getStorageSync('day') || {};
              storage[this.data.type] = true;
              wx.setStorage({
                key: day,
                data: storage
              })
              wx.redirectTo({
                url: '/pages/my/meal/index',
              })
              this.closeFile();
            } else {
              App.prompts(res.msg)
            }
          }).catch(err => {
          })
        }
      }
    });
  },
  // 合并
  setList() {
    let files = this.data.fileList;
    let dates = this.data.listDate;
    let arr = [];
    for (let i = 0; i < files.length; i++) {
      let param = {
        name: files[i].name,
        children: (dates.map(val => {
          let index = (val.types).findIndex(items => {
            return items.parent_id === files[i].uid
          })
          if (index !== -1) {
            val.number = 1;
            return val;
          }
        })).filter(val => val)
      };
      arr.push(param);
    }
    console.log('结果数据', arr);
    //以下代码为了展示右侧不同二次菜品分类
    let type = '';
    switch(this.data.type){
      case '1':
        type = '早餐';
        break;
      case '2':
        type = '中餐';
        break;
      case '3':
        type = '晚餐';
        break;
    }
    // 根据id筛选出早\午\晚
    let newList = arr.find(item=>{
      return item.name == type
    });
    if (newList){
      let typeObj = {};
      let typeList = [];
      console.log(newList)
      newList.children.map(item => {
        item.types.map(t => {
          if (t.parent_id && !typeObj[t.parent_id]) {
            typeObj[t.parent_id] = JSON.parse(JSON.stringify(t));
            typeObj[t.parent_id].children = [];
          }
          if (typeObj[t.parent_id]) {
            typeObj[t.parent_id].children.push(item);
          }
        })
      })
      Object.getOwnPropertyNames(typeObj).forEach(key => {
        typeList.push(typeObj[key])
      })
      this.setData({
        fileList: null,
        listDate: null,
        list: typeList,
        typeName: type
      })
    }else{
      this.setData({
        fileList: null,
        listDate: null,
        list: [],
        typeName: type
      })
    }
    
  },
  getList() {
    let url = 'mp/dishes/list';
    App.ajax(url, 'GET', '').then(res => {
      console.log('数据', res)
      if (res.status === 10000) {
        this.setData({
          // listDate: res.data = res.data.concat(res.data)
          listDate: res.data
        })
        if (this.data.fileList) this.setList();
      } else {
        App.prompts(res.msg);
      }
    }).catch(err => {
      console.log(err)
    })
  },
  fileList() {
    let url = 'mp/dishes/type';
    App.ajax(url, 'GET', '').then(res => {
      console.log('数据1', res)
      if (res.status === 10000) {
        this.setData({
          fileList: res.data
        })
        if (this.data.listDate) this.setList();
      } else {
        App.prompts(res.msg);
      }
    }).catch(err => {
      console.log(err)
    })
  }
})